package org.example.shop.service;

import org.example.shop.entity.Admin;
import org.example.shop.entity.User;
import org.example.shop.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminService adminService; // 注入AdminService

    public boolean isAccountExists(String account) {
        return userMapper.isAccountExists(account) > 0;
    }

    // 注册新用户
    public boolean insertUser(String account, String password, String email, String telphone) {
        if (isAccountExists(account)) {
            return false; // 用户名已存在，返回 false
        }

        User user = new User();
        user.setAccount(account);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setEmail(email);
        user.setTelphone(telphone);
        user.setPoints(0);
        user.setMoney(BigDecimal.valueOf(0.0));
        user.setRegTime(LocalDateTime.now());
        user.setStatus("Y");
        user.setAvatar("");
        int re = userMapper.insertUser(user);
        return re > 0;
    }

    public User validateUser(String account, String password) {
        // 管理员登录
        if (account.equals("admin")) {
            Admin admin = adminService.login(account, password);
            if (admin != null) {
                return new User(admin.getAccount(), admin.getPassword(), "admin");
            }
        } else {
            // 普通用户登录
            User user = userMapper.selectByAccount(account);
            if (user != null) {
                String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
                if (encryptedPwd.equals(user.getPassword())) {
                    return user;
                }
            }
        }
        return null;
    }
    public boolean register(String account, String password, String email, String telphone) {
        // 检查用户名是否已存在
        if (isAccountExists(account)) {
            return false;
        }

        // 加密密码
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        // 创建用户对象
        User user = new User();
        user.setAccount(account);
        user.setPassword(encryptedPassword);
        user.setEmail(email);
        user.setTelphone(telphone);
        user.setPoints(0);
        user.setMoney(BigDecimal.ZERO);
        user.setRegTime(LocalDateTime.now());
        user.setStatus("Y");
        user.setRole("user"); // 默认注册为普通用户
        user.setAvatar(""); // 默认头像为空

        // 插入用户数据
        int result = userMapper.insertUser(user);
        return result > 0;
    }
}